package com.xpffly.design.proxy.dynamic;

import com.xpffly.design.proxy.dynamic.service.GamePlayer;
import com.xpffly.design.proxy.dynamic.service.impl.GamePlayerReal;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: xpengfei
 * @Date: 2021/3/30 22:32
 * @Description：动态代理场景类
 */
public class Scene {

    public static void main(String[] args) {
        // 定义一个玩家
        GamePlayer gamePlayer = new GamePlayerReal("哈哈");
        // 定义一个handler
        InvocationHandler invocationHandler = new GamePlayerDynamicProxy(gamePlayer);
        System.out.println("游戏开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        // 获得类的classloader
        ClassLoader classLoader = gamePlayer.getClass().getClassLoader();
        // 动态产生一个代理者
        GamePlayer gamePlayerProxy = (GamePlayer) Proxy.newProxyInstance(classLoader, new Class[]{GamePlayer.class}, invocationHandler);
        // 登录
        gamePlayerProxy.login("张三", "password123");
        // 杀怪
        gamePlayerProxy.killBoss();
        // 升级
        gamePlayerProxy.upgrade();
        System.out.println("游戏结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
